package com.iqiyi.pps.epg.api.server.impl;

import com.alibaba.fastjson.JSONObject;
import com.iqiyi.mams.hedvig.rpc.client.ServiceHelper;
import com.iqiyi.pps.epg.api.model.web.query.TFilter;
import com.iqiyi.pps.epg.api.model.web.query.TPage;
import com.iqiyi.pps.epg.api.model.web.statistic.TStatisticOcrData;
import com.iqiyi.pps.epg.api.model.web.statistic.TStatisticProduceData;
import com.iqiyi.pps.epg.api.model.web.statistic.TStatisticProduceDataPage;
import com.iqiyi.pps.epg.api.model.web.statistic.TStatisticSty2Data;
import com.iqiyi.pps.epg.api.server.iservice.BasementApiService;
import com.iqiyi.pps.epg.api.server.proxy.ChannelProxy;
import com.iqiyi.pps.epg.api.server.proxy.OtherProxy;
import com.iqiyi.pps.epg.api.server.proxy.ProgramProxy;
import com.iqiyi.pps.epg.api.server.proxy.StreamProxy;
import com.iqiyi.pps.epg.api.server.web.qipu.QipuWebService;
import com.iqiyi.pps.epg.api.server.web.statistic.StatisticWebService;
import com.iqiyi.pps.epg.api.utils.*;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.ws.rs.core.Cookie;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MultivaluedMap;
import java.net.InetAddress;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


@Service("basementApiServiceImpl")
public class BasementApiServiceImpl extends ApiServiceImpl implements BasementApiService {
    private static Logger logger = LoggerFactory.getLogger(BasementApiServiceImpl.class);

    //直转点后制作相关数据统计
    public static final String STATISTIC_PRODUCE_TYPE = "BS_1_ST_1";
    //长视频只能分析数据统计
    public static final String STATISTIC_STY2_TYPE = "BS_1_ST_2";
    //直转点功能点使用情况统计
    public static final String STATISTIC_OCR_TYPE = "BS_1_ST_3";
    //直转点精确化裁剪统计
    public static final String STATISTIC_DETAIL_TYPE = "BS_1_ST_4";

    @Autowired
    private StreamProxy streamProxy;

    @Autowired
    private ProgramProxy programProxy;

    @Autowired
    private ChannelProxy channelProxy;

    @Autowired
    private OtherProxy otherProxy;

    @Override

    public String testMsg() {
        System.err.println("remoteIpPort=" + httpHeaders.getRequestHeader("X-Real-IP"));
        logger.error("************");
        logger.error("[test mesg]",httpHeaders.getRequestHeader("X-Real-IP") );
        logger.error("************");
        return Constants.getJsonResponse(Constants.CODE_SUC, null, httpHeaders.getRequestHeader("X-Real-IP")+"");

    }

    @Override
    public String getStreamNameSuggest(long fatherId, String streamName) {
        logger.info("[BasementApiServiceImpl][getStreamNameSuggest][Start][fatherId = {}, streamName = {}]", new Object[]{fatherId, streamName});
        CrossDataLocalPool.set(getCrossData());
        return streamProxy.getStreamNameSuggest(fatherId, streamName);
    }

    @Override
    public String createTs(String fatherId, String streamName, String streamIp) {
        logger.info("[BasementApiServiceImpl][createTs][Start][fatherId = {}, streamName = {}, streamIp = {}]", new Object[]{fatherId, streamName, streamIp});
        CrossDataLocalPool.set(getCrossData());
        return streamProxy.createTs(fatherId, streamName, streamIp);
    }

    @Override
    public String startTs(String fatherId, String streamName) {
        logger.info("[BasementApiServiceImpl][startTs][Start][fatherId = {}, streamName = {}]", new Object[]{fatherId, streamName});
        CrossDataLocalPool.set(getCrossData());
        return streamProxy.startTs(fatherId, streamName);
    }

    @Override
    public String stopTs(String fatherId, String streamName) {
        logger.info("[BasementApiServiceImpl][stopTs][Start][fatherId = {}, streamName = {}]", new Object[]{fatherId, streamName});
        CrossDataLocalPool.set(getCrossData());
        return streamProxy.stopTs(fatherId, streamName);
    }

    @Override
    public String deleteTs(String fatherId, String streamName) {
        logger.info("[BasementApiServiceImpl][deleteTs][Start][fatherId = {}, streamName = {}]", new Object[]{fatherId, streamName});
        CrossDataLocalPool.set(getCrossData());
        return streamProxy.deleteTs(fatherId, streamName);
    }

    @Override
    public String createFlv(String fatherId, String streamName, String isDefault, String streamIp) {
        logger.info("[BasementApiServiceImpl][createFlv][Start][fatherId = {}, streamName = {}, isDefault = {}, streamIp = {}]", new Object[]{fatherId, streamName, isDefault, streamIp});
        CrossDataLocalPool.set(getCrossData());
        return streamProxy.createFlv(fatherId, streamName, isDefault, streamIp);
    }

    @Override
    public String startFlv(String fatherId, String streamName) {
        logger.info("[BasementApiServiceImpl][createFlv][Start][fatherId = {}, streamName = {}]", new Object[]{fatherId, streamName});
        CrossDataLocalPool.set(getCrossData());
        return streamProxy.startFlv(fatherId, streamName);
    }

    @Override
    public String stopFlv(String fatherId, String streamName) {
        logger.info("[BasementApiServiceImpl][stopFlv][Start][fatherId = {}, streamName = {}]", new Object[]{fatherId, streamName});
        CrossDataLocalPool.set(getCrossData());
        return streamProxy.stopFlv(fatherId, streamName);
    }

    @Override
    public String deleteFlv(String fatherId, String streamName) {
        logger.info("[BasementApiServiceImpl][deleteFlv][Start][fatherId = {}, streamName = {}]", new Object[]{fatherId, streamName});
        CrossDataLocalPool.set(getCrossData());
        return streamProxy.deleteFlv(fatherId, streamName);
    }

    @Override
    public String createDolby(String fatherId, String streamName) {
        logger.info("[BasementApiServiceImpl][createDolby][Start][fatherId = {}, streamName = {}]",
                new Object[]{fatherId, streamName});
        CrossDataLocalPool.set(getCrossData());
        return streamProxy.createDolby(fatherId, streamName);

    }

    @Override
    public String startDolby(String fatherId, String streamName) {
        logger.info("[BasementApiServiceImpl][createDolby][Start][fatherId = {}, dolbyStreamName = {}]",
                new Object[]{fatherId, streamName});
        CrossDataLocalPool.set(getCrossData());
        return streamProxy.startDolby(fatherId, streamName);
    }

    @Override
    public String stopDolby(String fatherId, String streamName) {
        logger.info("[BasementApiServiceImpl][stopDolby][Start][fatherId = {}, streamName = {}]", new Object[]{fatherId, streamName});
        CrossDataLocalPool.set(getCrossData());
        return streamProxy.stopDolby(fatherId, streamName);
    }

    @Override
    public String deleteDolby(String fatherId, String streamName) {
        logger.info("[BasementApiServiceImpl][deleteDolby][Start][fatherId = {}, dolbyStreamName = {}]", new Object[]{fatherId, streamName});
        CrossDataLocalPool.set(getCrossData());
        return streamProxy.deleteDolby(fatherId, streamName);
    }

    @Override
    public String restartDolby(String fatherId, String streamName) {
        logger.info("[BasementApiServiceImpl][restartDolby][Start][fatherId = {}, dolbyStreamName = {}]",
                new Object[]{fatherId, streamName});
        CrossDataLocalPool.set(getCrossData());
        return streamProxy.restartDolby(fatherId, streamName);
    }

    @Override
    public String getLiveStream(String fatherId, String streamName, String formatType) {
        logger.info("[BasementApiServiceImpl][getLiveStream][Start][fatherId = {}, streamName = {}, formatType = {}]", new Object[]{fatherId, streamName, formatType});
        CrossDataLocalPool.set(getCrossData());
        return streamProxy.getLiveStream(fatherId, streamName, formatType);
    }

    @Override
    public String notifyChange(String user, String streamName, String streamServer, String streamUrl) {
        logger.info("[BasementApiServiceImpl][notifyChange][Start][user = {}, streamName = {}, streamServer = {}, streamUrl = {}]", new Object[]{user, streamName, streamServer,streamUrl});
        CrossDataLocalPool.set(getCrossData());
        return streamProxy.notifyChange(user,streamName,streamServer,streamUrl);
    }

    @Override
    public String streamMonitor(JSONObject jsonObject) {
        logger.info("[BasementApiServiceImpl][streamMonitor][Start][json = {}]", new Object[]{jsonObject});
        CrossDataLocalPool.set(getCrossData());
        String clientHost = httpHeaders.getRequestHeader("X-Real-IP")+"";
        jsonObject.put("clientHost", clientHost.substring(1,clientHost.length()-1));
        return streamProxy.streamMonitor(jsonObject);
    }

    @Override
    public String snapshotCall(String taskId, String snapshot, String errcode, String errmsg) {
        CrossDataLocalPool.set(getCrossData());
        return programProxy.snapshotCall(taskId, snapshot, errcode, errmsg);
    }

    @Override
    public String getConfigs(String type) {
        CrossDataLocalPool.set(getCrossData());
        return channelProxy.getConfigs(type);
    }

    @Override
    public String permission(String uri) {
        CrossDataLocalPool.set(getCrossData());
        return otherProxy.permission(uri);
    }

    @Override
    public String redirectRequest(String requestJson) {
        JSONObject entity = JSONObject.parseObject(requestJson);
        String url = entity.getString("url");
        JSONObject params = entity.getJSONObject("params");
        JSONObject headers = entity.getJSONObject("headers");
        String type = entity.getString("type");
        String result = null;
        Map<String, Object> headersMap = quickToMap(headers);
        if (url.startsWith("http://qipu-test.qiyi.domain/int/entity/nocache") || url.startsWith("http://qipu.qiyi.domain/int/entity/nocache")) {
            Pattern pattern = Pattern.compile("[0-9]+");
            Matcher matcher = pattern.matcher(url);
            if (matcher.find()) {
                String qipuId = matcher.group();
                QipuWebService.Iface service = ServiceHelper.getThriftService(QipuWebService.Iface.class);
                try {
                    result = service.getJsonEpisode(Long.parseLong(qipuId));
                    return result;
                } catch (Exception e) {
                    logger.error("[redirect][QipuWebService.getJsonEpisode]", e);
                    return ServiceUtil.getResponseError(INTERFACE_ERROR);
                }
            }
        }

        if (entity.containsKey("needCookie")) {
            MultivaluedMap<String, String> vars = httpHeaders.getRequestHeaders();
            Map<String, Cookie> map = new HashMap<String, Cookie>();
            String cookieValue = SsoUtil.getLegoLoginCookie(httpHeaders);
            logger.info("loginCookie" + cookieValue);
            if (cookieValue != null) {
                headersMap.put(HttpHeaders.COOKIE, SsoUtil.LEGO_USERID_COOKIE_KEY + "=" + cookieValue);
            }
        }
        if ("get".equalsIgnoreCase(type)) {
            result = ApiHttpRequestUtil.getMethod(url, headersMap, quickToMap(params));
        } else if ("post".equalsIgnoreCase(type)) {
            result = ApiHttpRequestUtil.postMethod(url, headersMap, quickToMap(params));
        }else if( "post-raw".equalsIgnoreCase(type)){
            result = ApiHttpRequestUtil.doPostRaw(  url,params.toJSONString() ).toJSONString();
        }
        if (result != null) {
            return result;
        }
        return null;
    }

    @Override
    public String passportRequest(String requestJson) {
        JSONObject entity = JSONObject.parseObject(requestJson);
        Map<String, String> _param = new HashMap();
        _param.put("url", entity.getString("url"));
        String url = entity.getString("url");
        JSONObject params = entity.getJSONObject("params");
        JSONObject headers = entity.getJSONObject("headers");
        String type = entity.getString("type");
        String result = null;
        Map<String, Object> headersMap = quickToMap(headers);
        if (entity.containsKey("needCookie")) {
            MultivaluedMap<String, String> vars = httpHeaders.getRequestHeaders();
            Map<String, Cookie> map = new HashMap<String, Cookie>();
            String cookieValue = SsoUtil.getLegoLoginCookie(httpHeaders);
            logger.info("loginCookie" + cookieValue);
            if (cookieValue != null) {
                headersMap.put(HttpHeaders.COOKIE, SsoUtil.LEGO_USERID_COOKIE_KEY + "=" + cookieValue);
            }
        }
        if ("post".equalsIgnoreCase(type)) {
            result = ApiPassportUtil.doQuery(url, headersMap, params);
        }
        if (result != null) {
            return result;
        }
        return null;
    }


    @Override
    public String restartFlv(String fatherId, String streamName, String internalIp, String streamIp) {
        logger.info("[BasementApiServiceImpl][restartFlv][Start][fatherId = {}, streamName = {}]", new Object[]{fatherId, streamName});
        CrossDataLocalPool.set(getCrossData());
        return streamProxy.restartFlv(fatherId, streamName, internalIp, streamIp);
    }

    @Override
    public String restartTs(String fatherId, String streamName, String internalIp, String streamIp) {
        logger.info("[BasementApiServiceImpl][restartFlv][Start][fatherId = {}, streamName = {}]", new Object[]{fatherId, streamName});
        CrossDataLocalPool.set(getCrossData());
        return streamProxy.restartTs(fatherId, streamName, internalIp, streamIp);
    }

    //  统计接口

    @Override
    public String statistic() {
        MultivaluedMap<String, String> multMap = uriInfo.getQueryParameters();
        String bs = String.valueOf(multMap.getFirst("bs"));   // 后台类型
        String st = String.valueOf(multMap.getFirst("st"));   // 统计类型

        if (!StringUtils.isNotBlank(bs) && !StringUtils.isNotBlank(st)) {
            logger.info("[statistic] bs、st参数不能为空");
            return ServiceUtil.getResponseError("[statistic] bs、st参数不能为空");
        }
        String baseQueryName = "BS_" + bs + "_ST_" + st;
        Map<String, String> _apiLog = new HashMap<String, String>();
        String strParam = net.sf.json.JSONObject.fromObject(multMap).toString();
        //直转点后制作相关数据统计
        if (STATISTIC_PRODUCE_TYPE.equals(baseQueryName)) {
            try {
                String serverIp = InetAddress.getLocalHost().getHostAddress();
                _apiLog = formatApiLogMap(serverIp, strParam);
                TStatisticProduceData tsp = new TStatisticProduceData();

                if (StringUtils.isNotBlank(multMap.getFirst("prid")))
                    tsp.setProgramId(Long.valueOf(multMap.getFirst("prid")));

                if (StringUtils.isNotBlank(multMap.getFirst("pr_name")))
                    tsp.setProgramName(String.valueOf(multMap.getFirst("pr_name")));

                if (StringUtils.isNotBlank(multMap.getFirst("pr_mins")))
                    tsp.setProgramMinutes(String.valueOf(multMap.getFirst("pr_mins")));

                if (StringUtils.isNotBlank(multMap.getFirst("cname")))
                    tsp.setChannelName(String.valueOf(multMap.getFirst("cname")));

                if (StringUtils.isNotBlank(multMap.getFirst("u")))
                    tsp.setUser(String.valueOf(multMap.getFirst("u")));

                if (StringUtils.isNotBlank(multMap.getFirst("cp")))
                    tsp.setCooperativePartiner(String.valueOf(multMap.getFirst("cp")));

                if (StringUtils.isNotBlank(multMap.getFirst("bt")))
                    tsp.setLiveBeginTime(String.valueOf(multMap.getFirst("bt")));

                if (StringUtils.isNotBlank(multMap.getFirst("et")))
                    tsp.setLiveEndTime(String.valueOf(multMap.getFirst("et")));

                if (StringUtils.isNotBlank(multMap.getFirst("dst")))
                    tsp.setDotSubTime(String.valueOf(multMap.getFirst("dst")));

                if (StringUtils.isNotBlank(multMap.getFirst("e_l_time")))
                    tsp.setEnterLegoTime(String.valueOf(multMap.getFirst("e_l_time")));

                if (null != multMap.getFirst("ablum_name")) {
                    tsp.setAlbumName(multMap.getFirst("ablum_name"));
                }

                if (StringUtils.isNotBlank(multMap.getFirst("s_a_dot")))
                    tsp.setStartAutoDot(Long.valueOf(multMap.getFirst("s_a_dot")));

                if (StringUtils.isNotBlank(multMap.getFirst("s_m_dot")))
                    tsp.setStartManualDot(Long.valueOf(multMap.getFirst("s_m_dot")));

                if (StringUtils.isNotBlank(multMap.getFirst("e_a_dot")))
                    tsp.setEndAutoDot(Long.valueOf(multMap.getFirst("e_a_dot")));

                if (StringUtils.isNotBlank(multMap.getFirst("e_m_dot")))
                    tsp.setEndManualDot(Long.valueOf(multMap.getFirst("e_m_dot")));

                if (StringUtils.isNotBlank(multMap.getFirst("ad_info")))
                    tsp.setAdInfo(String.valueOf(multMap.getFirst("ad_info")));

                if (RegUtil.isPositiveInteger(multMap.getFirst("ocr_flag"))) {
                    tsp.setOcrFlag(Integer.valueOf(multMap.getFirst("ocr_flag")));
                }
                if (RegUtil.isPositiveInteger(multMap.getFirst("ocr_title_flag"))) {
                    tsp.setOcrTitleFlag(Integer.valueOf(multMap.getFirst("ocr_title_flag")));
                }
                if (RegUtil.isDateFormat(multMap.getFirst("intelligent_insert_time"))) {
                    tsp.setIntelligentInsertTime(multMap.getFirst("intelligent_insert_time"));
                }
                if (RegUtil.isNonnegativeInteger(multMap.getFirst("data_mode"))) {
                    tsp.setDataMode(Integer.valueOf(multMap.getFirst("data_mode")));
                }
                if (RegUtil.isPositiveInteger(multMap.getFirst("statistic_id"))) {
                    tsp.setId(Long.valueOf(multMap.getFirst("statistic_id")));
                }
                StatisticWebService.Iface service = ServiceHelper.getThriftService(StatisticWebService.Iface.class);
                long resultId = service.saveProduceData(tsp);
                logger.info("[EPG][API][statistic][type={}]", STATISTIC_PRODUCE_TYPE);
                if(resultId < 0){
                    return ServiceUtil.getResponseError("STATISTIC_PRODUCE添加失败");
                }
                JSONObject data = new JSONObject();
                data.put("affectNum", 1);
                data.put("entityId", resultId);
                return Constants.getJsonResponse(Constants.CODE_SUC, data, "STATISTIC_PRODUCE添加成功");
            } catch (Exception e) {
                logger.error("[EPG][API][statistic][type=" + STATISTIC_PRODUCE_TYPE + "][error]", e);
                return ServiceUtil.getResponseError("STATISTIC_PRODUCE添加失败");
            } finally {
                _apiLog.put("resTime", String.valueOf(System.currentTimeMillis()));
                _apiLog.put("response", STATISTIC_PRODUCE_TYPE);
                insertInterfaceLog(_apiLog);
            }
        } else if (STATISTIC_STY2_TYPE.equals(baseQueryName)) {
            try {
                String serverIp = InetAddress.getLocalHost().getHostAddress();
                _apiLog = formatApiLogMap(serverIp, strParam);
                TStatisticSty2Data tStatisticSty2Data = new TStatisticSty2Data();
                String channelId = multMap.getFirst("channelId");
                String channelName = multMap.getFirst("channelName");
                String channelCode = multMap.getFirst("channelCode");
                String programId = multMap.getFirst("programId");
                String programName = multMap.getFirst("programName");
                String categoryName = multMap.getFirst("categoryName");
                String albumName = multMap.getFirst("albumName");
                String programTime = multMap.getFirst("programTime");
                String headerCompleteNumbers = multMap.getFirst("headerCompleteNumbers");
                String headerIncompleteNumbers = multMap.getFirst("headerIncompleteNumbers");
                String headerFaultNumbers = multMap.getFirst("headerFaultNumbers");
                String lastCompleteNumbers = multMap.getFirst("lastCompleteNumbers");
                String lastIncompleteNumbers = multMap.getFirst("lastIncompleteNumbers");
                String lastFaultNumbers = multMap.getFirst("lastFaultNumbers");
                String adCompleteNumbers = multMap.getFirst("adCompleteNumbers");
                String adIncompleteNumbers = multMap.getFirst("adIncompleteNumbers");
                String adFaultNumbers = multMap.getFirst("adFaultNumbers");
                String user = multMap.getFirst("user");

                tStatisticSty2Data.setChannelId(channelId);
                tStatisticSty2Data.setChannelName(channelName);
                tStatisticSty2Data.setChannelCode(channelCode);
                tStatisticSty2Data.setProgramId(programId);
                tStatisticSty2Data.setProgramName(programName);
                tStatisticSty2Data.setCategoryName(categoryName);
                tStatisticSty2Data.setAlbumName(albumName);
                tStatisticSty2Data.setProgramTime(Integer.parseInt(programTime));
                tStatisticSty2Data.setHeaderCompleteNumbers(headerCompleteNumbers);
                tStatisticSty2Data.setHeaderIncompleteNumbers(headerIncompleteNumbers);
                tStatisticSty2Data.setHeaderFaultNumbers(headerFaultNumbers);
                tStatisticSty2Data.setLastCompleteNumbers(lastCompleteNumbers);
                tStatisticSty2Data.setLastIncompleteNumbers(lastIncompleteNumbers);
                tStatisticSty2Data.setLastFaultNumbers(lastFaultNumbers);
                tStatisticSty2Data.setAdCompleteNumbers(adCompleteNumbers);
                tStatisticSty2Data.setAdIncompleteNumbers(adIncompleteNumbers);
                tStatisticSty2Data.setAdFaultNumbers(adFaultNumbers);
                tStatisticSty2Data.setUser(user);

                StatisticWebService.Iface service = ServiceHelper.getThriftService(StatisticWebService.Iface.class);
                String result = service.saveSty2Data(tStatisticSty2Data);
                logger.info("[EPG][API][statistic][type={}][result={}]", STATISTIC_STY2_TYPE, Constants.getCode(result));
                JSONObject data = new JSONObject();
                return Constants.getJsonResponse(Constants.CODE_SUC, data, "STATISTIC_STY2添加成功");
            } catch (Exception e) {
                logger.error("[EPG][API][statistic][type=" + STATISTIC_STY2_TYPE + "][error]", e);
                return ServiceUtil.getResponseError("STATISTIC_STY2添加失败");
            } finally {
                _apiLog.put("resTime", String.valueOf(System.currentTimeMillis()));
                _apiLog.put("response", STATISTIC_STY2_TYPE);
                insertInterfaceLog(_apiLog);
            }
        }
        if (STATISTIC_OCR_TYPE.equals(baseQueryName)) {
            try {
                String serverIp = InetAddress.getLocalHost().getHostAddress();
                _apiLog = formatApiLogMap(serverIp, strParam);
                TStatisticOcrData ocrData = new TStatisticOcrData();

                String channelId = multMap.getFirst("channelId");             //频道ID
                String channelName = multMap.getFirst("channelName");         //频道名称
                String programId = multMap.getFirst("programId");             //节目ID
                String programName = multMap.getFirst("programName");         //节目原名
                String categoryName = multMap.getFirst("categoryName");       //频道（打点）名称
                String ocrReturnTitle = multMap.getFirst("ocrTitle");         //OCR提示标题
                String userSubmitTitle = multMap.getFirst("userTitle");       //编辑输入标题
                String user = multMap.getFirst("user");                       //制作人员

                if (StringUtils.isEmpty(ocrReturnTitle) || StringUtils.isEmpty(userSubmitTitle)) {
                    return ServiceUtil.getResponseError("STATISTIC_OCR参数错误");
                }
                ocrData.setChannelId(channelId);
                ocrData.setChannelName(channelName);
                ocrData.setProgramId(programId);
                ocrData.setProgramName(programName);
                ocrData.setCategoryName(categoryName);
                ocrData.setOcrReturnTitle(ocrReturnTitle);
                ocrData.setUserSubmitTitle(userSubmitTitle);
                ocrData.setUser(user);
                StatisticWebService.Iface service = ServiceHelper.getThriftService(StatisticWebService.Iface.class);
                String result = service.saveOcrData(ocrData);
                logger.info("[EPG][API][statistic][type={}][result={}]", STATISTIC_OCR_TYPE, Constants.getCode(result));
                JSONObject data = new JSONObject();
                return Constants.getJsonResponse(Constants.CODE_SUC, data, "添加成功");
            } catch (Exception e) {
                logger.error("[EPG][API][statistic][type={}][error]", STATISTIC_OCR_TYPE, e);
                return ServiceUtil.getResponseError("STATISTIC_OCR参数错误");
            } finally {
                _apiLog.put("resTime", String.valueOf(System.currentTimeMillis()));
                _apiLog.put("response", STATISTIC_OCR_TYPE);
                insertInterfaceLog(_apiLog);

            }
        } else if (STATISTIC_DETAIL_TYPE.equals(baseQueryName)) {
            String channelId = multMap.getFirst("channelId");             //频道ID
            String categoryName = multMap.getFirst("categoryName");       //频道（打点）名称
            String userActionCount = multMap.getFirst("userActionCount");         //编辑主动精确化裁剪次数
            String systemInfoCount = multMap.getFirst("systemInfoCount");        //系统强制精确化裁剪次数
            String user = multMap.getFirst("userName");                    //制作人员的邮箱
        }
        JSONObject data = new JSONObject();
        return Constants.getJsonResponse(Constants.CODE_SUC, data, "添加成功");
    }

    @Override
    public String getStatistic() {
        String type = String.valueOf(uriInfo.getQueryParameters().getFirst("type"));   // 类型
        String jsonStrResp = "";
        Integer pageNo = null;
        Integer pageSize = null;
        if (StringUtils.isNotBlank(uriInfo.getQueryParameters().getFirst("pageNo"))) {
            pageNo = Integer.parseInt(uriInfo.getQueryParameters().getFirst("pageNo"));
        }
        if (StringUtils.isNotBlank(uriInfo.getQueryParameters().getFirst("pageSize"))) {
            pageSize = Integer.parseInt(uriInfo.getQueryParameters().getFirst("pageSize"));
        }

        pageNo = (pageNo == null || pageNo < 1) ? 1 : pageNo;
        pageSize = (pageSize == null || pageSize < 1) ? 20 : pageSize;
        TStatisticProduceDataPage tStatisticProduceDataPage = new TStatisticProduceDataPage();
        if (StringUtils.isNotBlank(uriInfo.getQueryParameters().getFirst("exportExcel"))) {
            pageSize = 1000;   //  导出EXECL为1000条
        }
        tStatisticProduceDataPage.setTPage(new TPage(-1, pageNo, pageSize, "id", "desc", true));

        switch (type) {
            case "pd":

                try {
                    TFilter tFilter = new TFilter();
                    Map<String, String> params = new HashMap<>();
                    if (StringUtils.isNotBlank(uriInfo.getQueryParameters().getFirst("b_date"))) {
                        params.put("bDate", uriInfo.getQueryParameters().getFirst("b_date"));
                    }
                    if (StringUtils.isNotBlank(uriInfo.getQueryParameters().getFirst("e_date"))) {
                        params.put("eDate", uriInfo.getQueryParameters().getFirst("e_date"));
                    }
                    if (StringUtils.isNotBlank(uriInfo.getQueryParameters().getFirst("live_b_date"))) {
                        params.put("live_b_date", uriInfo.getQueryParameters().getFirst("live_b_date"));
                    }
                    if (StringUtils.isNotBlank(uriInfo.getQueryParameters().getFirst("live_e_date"))) {
                        params.put("live_e_date", uriInfo.getQueryParameters().getFirst("live_e_date"));
                    }

                    if (StringUtils.isNotBlank(uriInfo.getQueryParameters().getFirst("ocrFlag"))) {
                        params.put("ocr_flag", uriInfo.getQueryParameters().getFirst("ocrFlag"));
                    }
                    if (StringUtils.isNotBlank(uriInfo.getQueryParameters().getFirst("ocrTitleFlag"))) {
                        params.put("ocr_title_flag", uriInfo.getQueryParameters().getFirst("ocrTitleFlag"));
                    }

                    if (StringUtils.isNotBlank(uriInfo.getQueryParameters().getFirst("sPrMins"))) {
                        params.put("sPrMins", uriInfo.getQueryParameters().getFirst("sPrMins"));
                    }
                    if (StringUtils.isNotBlank(uriInfo.getQueryParameters().getFirst("ePrMins"))) {
                        params.put("ePrMins", uriInfo.getQueryParameters().getFirst("ePrMins"));
                    }
                    if (StringUtils.isNotBlank(uriInfo.getQueryParameters().getFirst("cname"))) {
                        params.put("cName", uriInfo.getQueryParameters().getFirst("cname"));
                    }
                    if (StringUtils.isNotBlank(uriInfo.getQueryParameters().getFirst("u"))) {
                        params.put("u", uriInfo.getQueryParameters().getFirst("u"));
                    }
                    if (StringUtils.isNotBlank(uriInfo.getQueryParameters().getFirst("cp"))) {
                        params.put("cp", uriInfo.getQueryParameters().getFirst("cp"));
                    }
                    if (StringUtils.isNotBlank(uriInfo.getQueryParameters().getFirst("pr_name"))) {
                        params.put("prName", uriInfo.getQueryParameters().getFirst("pr_name"));
                    }
                    if (StringUtils.isNotBlank(uriInfo.getQueryParameters().getFirst("bt"))) {
                        params.put("bt", uriInfo.getQueryParameters().getFirst("bt"));
                    }
                    if (StringUtils.isNotBlank(uriInfo.getQueryParameters().getFirst("et"))) {
                        params.put("et", uriInfo.getQueryParameters().getFirst("et"));
                    }
                    if (StringUtils.isNotBlank(uriInfo.getQueryParameters().getFirst("program_id"))) {
                        params.put("program_id", uriInfo.getQueryParameters().getFirst("program_id"));
                    }

                    params.put("pageNo", pageNo + "");
                    params.put("pageSize", pageSize + "");
                    tFilter.setFilters(params);

                    TStatisticProduceData tsp = new TStatisticProduceData();

                    StatisticWebService.Iface service = ServiceHelper.getThriftService(StatisticWebService.Iface.class);
                    tStatisticProduceDataPage = service.getProduceData(tStatisticProduceDataPage.getTPage(), tFilter);
                    if (tStatisticProduceDataPage != null) {
                        jsonStrResp = Constants.getResponse(Constants.CODE_SUC, tStatisticProduceDataPage, null).toJsonString();
                    } else {
                        jsonStrResp = Constants.getJsonResponse(Constants.CODE_ERROR, null, "参数错误");
                    }
                } catch (Exception e) {
                    logger.error("[EPG][API][getProduceData][error]", e);
                }
                break;
        }
        return jsonStrResp;
    }

    @Override
    public String statisticOcrList(String startDate, String endDate, Integer pageNo, Integer pageSize,
                                   String channelId, String categoryName, String user) {
        CrossDataLocalPool.set(getCrossData());
        return otherProxy.statisticOcrList(startDate, endDate, pageNo, pageSize,
                channelId, categoryName, user);

    }

    @Override
    public String statisticSty2List(String startDate, String endDate, Integer pageNo, Integer pageSize,
                                    String channelId, String channelName, String programName, String albumName,
                                    String categoryName, String user) {
        logger.info("[BasementApiServiceImpl][statisticSty2List][start]");
        CrossDataLocalPool.set(getCrossData());
        return otherProxy.statisticSty2List(startDate, endDate, pageNo, pageSize,
                channelId, channelName, programName, albumName,
                categoryName, user);
    }

    @Override
    public String statisticSty2PercentList(String startDate, String endDate, String channelName,
                                           String albumName, String categoryName) {
        logger.info("[BasementApiServiceImpl][statisticSty2PercentList][start]");
        CrossDataLocalPool.set(getCrossData());
        return otherProxy.statisticSty2PercentList(startDate, endDate, channelName,
                albumName, categoryName);
    }

    @Override
    public String newsDetailsList(Integer pageNo, Integer pageSize, String newsName, String channelName, String serverRegion, String serverIp, String startDate, String endDate) {
        logger.info("[BasementApiServiceImpl][newsDetailsList][start]");
        CrossDataLocalPool.set(getCrossData());
        return otherProxy.newsDetailsList(pageNo, pageSize, newsName, channelName,
                serverRegion, serverIp, startDate, endDate);
    }

    @Override
    public String statisticNewsDetailsList(Integer pageNo, Integer pageSize, String newsName, String channelName,
                                           String serverRegion, String serverIp, String startDate, String endDate) {
        logger.info("[BasementApiServiceImpl][statisticNewsDetailsList][start]");
        CrossDataLocalPool.set(getCrossData());
        return otherProxy.statisticNewsDetailsList(pageNo, pageSize, newsName, channelName,
                serverRegion, serverIp, startDate, endDate);
    }

    @Override
    public String newsDetailsAdd(String dataString) {
        CrossDataLocalPool.set(getCrossData());
        return otherProxy.newsDetailsAdd(dataString);
    }

    @Override
    public String suggestChannelInfo(String channelQipuId, String channelName, String liveType) {
        CrossDataLocalPool.set(getCrossData());
        return channelProxy.suggestChannelInfo(channelQipuId, channelName, liveType);
    }

    @Override
    public String suggestStatisticSty2(String field, String word) {
        logger.info("[BasementApiServiceImpl][suggestStatisticSty2][start]");
        CrossDataLocalPool.set(getCrossData());
        return otherProxy.suggestStatisticSty2(field, word);
    }

    @Override
    public String modifyAdvert(Long programId, Integer enable) {
        CrossDataLocalPool.set(getCrossData());
        return programProxy.modifyAdvert(programId, enable);
    }

    @Override
    public String getDuBiStreamNameSuggest(String streamName, int encodeType) {
        CrossDataLocalPool.set(getCrossData());
        return streamProxy.getDuBiStreamNameSuggest(streamName, encodeType);
    }

    @Override
    public String geth265StreamNameSuggest(String streamName) {
        CrossDataLocalPool.set(getCrossData());
        return streamProxy.geth265StreamNameSuggest(streamName);
    }

    @Override
    public String createNewTs(String fatherId, String streamName) {
        CrossDataLocalPool.set(getCrossData());
        return streamProxy.createNewTs(fatherId, streamName);
    }

    @Override
    public String startNewTs(String fatherId,
                             String streamName) {
        logger.info("[BasementApiServiceImpl][startNewTs][Start][fatherId = {}, StreamName = {}]",
                new Object[]{fatherId, streamName});
        CrossDataLocalPool.set(getCrossData());
        return streamProxy.startNewTs(fatherId, streamName);
    }

    @Override
    public String stopNewTs(String fatherId,
                            String streamName) {
        logger.info("[BasementApiServiceImpl][stopNewTs][Start][fatherId = {}, streamName = {}]", new Object[]{fatherId, streamName});
        CrossDataLocalPool.set(getCrossData());
        return streamProxy.stopNewTs(fatherId, streamName);
    }


    @Override
    public String deleteNewTs(String fatherId, String streamName) {
        logger.info("[BasementApiServiceImpl][deleteNewTs][Start][fatherId = {}, streamName = {}]", new Object[]{fatherId, streamName});
        CrossDataLocalPool.set(getCrossData());
        return streamProxy.deleteNewTs(fatherId, streamName);
    }

    @Override
    public String restartNewTs(String fatherId, String streamName) {
        logger.info("[BasementApiServiceImpl][restartNewTs][Start][fatherId = {}, streamName = {}]",
                new Object[]{fatherId, streamName});

        CrossDataLocalPool.set(getCrossData());
        return streamProxy.restartNewTs(fatherId, streamName);
    }

    @Override
    public String addConfig(String data) {
        CrossDataLocalPool.set(getCrossData());
        return otherProxy.addConfig(data);
    }

    @Override
    public String editConfig(String data) {
        CrossDataLocalPool.set(getCrossData());
        return otherProxy.editConfig(data);
    }

    @Override
    public String queryConfigs(String type, String status, String descr) {
        CrossDataLocalPool.set(getCrossData());
        return otherProxy.queryConfigs(type,status,descr);
    }

    @Override
    public String sendNotify(String data){
        CrossDataLocalPool.set(getCrossData());
        return otherProxy.doSendAlert(data);
    }

}

